package com.zg.autoflow.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zg.autoflow.req.AutoflowExtendsAddReq;
import com.zg.autoflow.service.AutoflowExtendsService;
import com.zg.common.core.dao.autoflow.dao.AutoflowExtendsDao;
import com.zg.common.core.dao.autoflow.entity.AutoflowExtends;
import com.zg.common.core.exception.BusinessException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
* @author zg
*/
@Service
@RequiredArgsConstructor
public class AutoflowExtendsServiceImpl implements AutoflowExtendsService {

    private final AutoflowExtendsDao autoflowExtendsDao;

    void checkAdd(AutoflowExtendsAddReq param) {
        LambdaQueryWrapper<AutoflowExtends> autoflowExtendsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        autoflowExtendsLambdaQueryWrapper
                .eq(AutoflowExtends::getSourceFlowId, param.getSourceFlowId())
                .eq(AutoflowExtends::getSourceStepId, param.getSourceStepId())
                .eq(AutoflowExtends::getSourceFormId, param.getSourceFormId())
                .eq(AutoflowExtends::getSourceColumn, param.getSourceColumn())
                .eq(AutoflowExtends::getTargetFlowId, param.getTargetFlowId())
                .eq(AutoflowExtends::getTargetStepId, param.getTargetStepId())
                .eq(AutoflowExtends::getTargetFormId, param.getTargetFormId())
                .eq(AutoflowExtends::getTargetColumn, param.getTargetColumn());
        if (autoflowExtendsDao.exists(autoflowExtendsLambdaQueryWrapper)) {
            BusinessException.happen("已存在相同的继承关系");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AutoflowExtends add(AutoflowExtendsAddReq param) {
        //校验逻辑
        checkAdd(param);
        //创建对象
        AutoflowExtends obj = new AutoflowExtends();
        //属性处理
        BeanUtil.copyProperties(param, obj);
        StringBuffer strBuff = new StringBuffer();
        obj.setSearchStr(strBuff.toString());
        //保存对象
        autoflowExtendsDao.save(obj);
        return obj;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void del(@RequestParam("ids") List<Long> idList) {
        autoflowExtendsDao.removeBatchByIds(idList);
    }

}
